import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_user_account.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/mine/account/widget/account_details_widget.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';

import '../../../bean/bean_category.dart';
import '../../../bean/bean_integral.dart';
import '../../catalogue/catalogue_article_page.dart';
import '../../study/main_video_v2_page.dart';
import '../../topic/topic_select_page.dart';
import '../new/score/mine_my_his_recoder_page.dart';
import '../new/score/mine_my_score_page.dart';
import 'controller/account_center_controller.dart';
import 'goods_list_page.dart';
import 'order_list_page.dart';

class AccountCenterPage extends StatefulWidget {
  final String tag;

  final bool showTitle;

  const AccountCenterPage({Key key, this.tag, this.showTitle = true})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return AccountCenterPageState();
  }
}

class AccountCenterPageState extends State<AccountCenterPage>
    with SingleTickerProviderStateMixin {
  AccountCenterController userController;
  String _tag;
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tag = widget.tag;
    userController = Get.put(AccountCenterController(), tag: _tag);
    _tabController = new TabController(length: 3, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffafafa),
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            Positioned(
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xFF90CAF9),
                      Colors.white,
                    ],
                  ),
                ),
              ),
            ),
            Positioned.fill(
              child: Scaffold(
                backgroundColor: Colors.transparent,
                appBar: widget.showTitle
                    ? AppBar(
                        backgroundColor: Colors.transparent,
                        elevation: 0,
                        title: Text("积分中心"),
                      )
                    : null,
                body: RefreshIndicator(
                  notificationPredicate: (ScrollNotification notification) {
                    return true;
                  },
                  onRefresh: () {
                    return Get.find<AccountCenterController>(tag: _tag)
                        .onRefresh();
                  },
                  child: NestedScrollView(
                    headerSliverBuilder: (
                      BuildContext context,
                      bool innerBoxIsScrolled,
                    ) {
                      return [
                        SliverToBoxAdapter(
                          child: Container(
                            padding: EdgeInsets.only(top: 12),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                AccountDetailsWidget(tag: _tag),
                                Container(
                                  margin: EdgeInsets.only(
                                      bottom: 8, left: 12, top: 12, right: 12),
                                  padding: EdgeInsets.all(10),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(4),
                                    ),
                                  ),
                                  child: Row(
                                    children: [
                                      buildItemClass(
                                        "积分记录",
                                        "assets/images/2.0x/paihang_icon",
                                        MyScorePage(
                                          scoreRankType: ScoreRankType
                                              .integralStatisticsRecoder,
                                        ),
                                      ),
                                      buildItemClass(
                                          "兑换中心",
                                          "assets/images/2.0x/collecg_icon",
                                          GoodsListPage(tag: widget.tag)),
                                      buildItemClass(
                                          "我的兑换",
                                          "assets/images/2.0x/score_icon",
                                          OrderListPage()),
                                    ],
                                  ),
                                ),
                                Container(
                                  alignment: Alignment.centerLeft,
                                  padding: EdgeInsets.only(top: 10, bottom: 10),
                                  child: TabBar(
                                    indicatorColor: Colors.blue[900],
                                    labelColor: Colors.blue[900],
                                    isScrollable: true,
                                    controller: _tabController,
                                    indicatorSize: TabBarIndicatorSize.label,
                                    tabs: [
                                      Tab(
                                        text: "我的任务",
                                      ),
                                      Tab(
                                        text: "任务明细",
                                      ),
                                      Tab(
                                        text: "积分明细",
                                      )
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                      ];
                    },
                    body: Container(
                      child: TabBarView(
                        controller: _tabController,
                        children: [
                          buildTaskListWidget(),
                          buildTaskDetailsWidget(),
                          buildAccountWaterWidget(),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///任务列表
  buildTaskListWidget() {
    return GetBuilder(
      id: "taskList",
      tag: _tag,
      builder: (AccountCenterController controller) {
        List<TaskBean> taskList = controller.taskList;
        List<TaskBean> taskList2 = controller.taskList2;
        bool waterListLoading = controller.waterListLoading;

        int itemCount = taskList.length + 1;
        if (taskList2.isNotEmpty) {
          itemCount = itemCount + taskList2.length + 1;
        }

        if (waterListLoading) {
          return Center(
            child: LoadingWidget(),
          );
        }

        LogUtils.e(" 列表 getbuilder $itemCount");

        if (itemCount == 1) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  controller.requestTaskList(click: true);
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      "assets/images/2.0x/home_study.png",
                      width: 33,
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(
                      "暂无数据",
                      style: TextStyle(color: Colors.grey),
                    )
                  ],
                ),
              )
            ],
          );
        }

        return Container(
          margin: EdgeInsets.only(bottom: 8, left: 12, right: 12),
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0xFFE3F2FD), Color(0xFFBBDEFB)]),
              borderRadius: BorderRadius.all(Radius.circular(12)),
              border: Border.all(
                color: Colors.white,
              )),
          child: Container(
            child: ListView.builder(
              itemCount: itemCount,
              itemBuilder: (BuildContext context, int index) {
                return buildTaskListItemWidget(
                    taskList, taskList2, index, controller);
              },
            ),
          ),
        );
      },
    );
  }

  ///构建任务条目
  buildTaskListItemWidget(List<TaskBean> taskList, List<TaskBean> taskList2,
      int index, AccountCenterController accountCenterController) {
    if (index == 0) {
      return Padding(
        padding: EdgeInsets.only(bottom: 0, top: 6),
        child: Row(
          children: [
            SizedBox(width: 8),
            Expanded(
              child: Container(
                child: Text(
                  "",
                  style: TextStyle(
                      fontWeight: FontWeight.w600, color: Colors.black),
                ),
              ),
            ),
            SizedBox(width: 4),
            Text(
              "",
              style: TextStyle(
                fontSize: 12,
                color: Color(0xff777777),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(top: 2),
              child: Icon(
                Icons.arrow_forward_ios_outlined,
                color: Colors.transparent,
                size: 12,
              ),
            ),
            SizedBox(width: 4),
          ],
        ),
      );
    } else if (index == taskList.length + 1) {
      return Padding(
        padding: EdgeInsets.only(bottom: 0, top: 12),
        child: Row(
          children: [
            SizedBox(width: 8),
            Expanded(
              child: Container(
                child: Text(
                  "",
                  style: TextStyle(
                      fontWeight: FontWeight.w600, color: Colors.black),
                ),
              ),
            ),
            SizedBox(width: 4),
          ],
        ),
      );
    }
    TaskBean item;
    bool showBoTo = false;
    if (index <= taskList.length) {
      showBoTo = true;
      item = taskList[index - 1];
    } else {
      showBoTo = false;
      item = taskList2[index - taskList.length - 1 - 1];
    }

    IconData iconData = Icons.book;
    //任务类型 0 阅读 ； 1 学习；2 看视频
    if (item.taskFlag == 0) {
      iconData = Icons.book;
    } else if (item.taskFlag == 1) {
      iconData = Icons.work;
    } else if (item.taskFlag == 2) {
      iconData = Icons.video_collection;
    }

    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
              color: Colors.white,
              padding: EdgeInsets.only(left: 12, top: 12, right: 12),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Container(
                            width: 58,
                            height: 58,
                            child: Row(
                              children: [
                                ClipOval(
                                  child: Container(
                                    color: Color(0xFFE3F2FD),
                                    padding: EdgeInsets.all(4),
                                    child: Stack(
                                      alignment: Alignment.center,
                                      children: [
                                        Icon(
                                          iconData,
                                          color: Colors.blue[900],
                                          size: 16,
                                        ),
                                        SizedBox(
                                          child: CircularProgressIndicator(
                                            strokeWidth: 2,
                                            value: item.taskCount /
                                                item.taskNumber,
                                          ),
                                          width: 26,
                                          height: 26,
                                        )
                                      ],
                                    ),
                                  ),
                                )
                              ],
                            ),
                          )
                        ],
                      ),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.center,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Row(
                              children: [
                                Container(
                                  margin: EdgeInsets.only(top: 2),
                                  child: ClipOval(
                                    child: Container(
                                      width: 11,
                                      height: 11,
                                      child: Icon(
                                        Icons.code,
                                        color: Colors.white,
                                        size: 6,
                                      ),
                                      color: Colors.blue[900],
                                    ),
                                  ),
                                ),
                                SizedBox(width: 8),
                                Text(
                                  item.showTaskInfo,
                                  style: TextStyle(
                                      fontSize: 10, color: Color(0xff666666)),
                                ),
                                SizedBox(width: 8),
                                Text(
                                  item.showFinishInfo,
                                  style: TextStyle(
                                      fontSize: 10, color: Color(0xff666666)),
                                )
                              ],
                            ),
                            SizedBox(height: 2),
                            Text(
                              item.taskName,
                              style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.black),
                            ),
                            SizedBox(
                              height: 6,
                            ),
                            Text(
                              item.taskInfo,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: 12, color: Color(0xff666666)),
                            )
                          ],
                        ),
                      ),
                      if (showBoTo)
                        ClipRRect(
                          borderRadius: BorderRadius.all(Radius.circular(22)),
                          child: GestureDetector(
                            onTap: () async {
                              //任务类型 0 阅读 ； 1 学习；2 看视频
                              if (item.taskFlag == 0) {
                                // await Get.to(() => AccountTaskDetailsPage(
                                //       tag: "taskmin0",
                                //       taskId: item.id,
                                //     ));
                                await Get.to(
                                  () => CatalogueArticleMainPage(
                                    taskId: item.id,
                                  ),
                                );
                              } else if (item.taskFlag == 1) {
                                // await Get.to(() =>
                                //     AccountTaskDetailsPage(
                                //       tag: "taskmin",
                                //       taskId: item.id,
                                //     ));
                                //任务中的题分类
                                List<CategoryBean> studyCategoryList =
                                    item.appStudyCategoryList;
                                if (studyCategoryList == null ||
                                    studyCategoryList.isEmpty) {
                                  ToastUtils.showToast("未查询到相关配置");
                                } else {
                                  CategoryBean one = studyCategoryList[0];
                                  await Get.to(
                                    () => TopicSelectPage(
                                      taskId: item.id,
                                      pageTitle: "${one.categoryName}",
                                      categoryOne: one.categoryCode,
                                    ),
                                  );
                                }
                              } else if (item.taskFlag == 2) {
                                // await Get.to(() => AccountTaskDetailsPage(
                                //       tag: "taskmin2",
                                //       taskId: item.id,
                                //     ));
                                await Get.to(
                                  () => VideoStudyMainV2Page(
                                    taskId: item.id,
                                  ),
                                );
                              }
                              accountCenterController.initRequest();
                            },
                            child: Container(
                              color: item.taskNumber > item.taskCount
                                  ? Colors.black
                                  : Colors.deepOrange,
                              padding: EdgeInsets.only(
                                  left: 12, right: 12, top: 2, bottom: 4),
                              child: Text(
                                item.taskNumber > item.taskCount
                                    ? "去查看"
                                    : "已达标",
                                style: TextStyle(
                                  fontSize: 12,
                                  color: item.taskNumber > item.taskCount
                                      ? Color(0xFFF2D999)
                                      : Colors.white,
                                ),
                              ),
                            ),
                          ),
                        )
                      else
                        SizedBox()
                    ],
                  ),
                  Container(
                    width: double.infinity,
                    height: 1,
                    color: Color(0xffeeeeee),
                    margin: EdgeInsets.only(top: 10),
                  )
                ],
              ))
        ],
      ),
    );
  }

  ///任务列表
  buildTaskDetailsWidget() {
    return GetBuilder(
      id: "taskDetailsList",
      tag: _tag,
      builder: (AccountCenterController controller) {
        List<TaskBeanDetails> taskDetailsList = controller.taskDetailsList;

        bool taskDetailsLoading = controller.taskDetailsLoading;
        if (taskDetailsLoading) {
          return LoadingWidget();
        }

        if (taskDetailsList == null || taskDetailsList.isEmpty) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  controller.requestTaskDetailsList(click: true);
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      "assets/images/2.0x/home_study.png",
                      width: 33,
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(
                      "暂无数据",
                      style: TextStyle(color: Colors.grey),
                    )
                  ],
                ),
              )
            ],
          );
        }
        return Container(
          margin: EdgeInsets.only(bottom: 8, left: 12, right: 12),
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0xFFE3F2FD), Color(0xFFBBDEFB)]),
              borderRadius: BorderRadius.all(Radius.circular(12)),
              border: Border.all(
                color: Colors.white,
              )),
          child: ListView.builder(
            itemCount: taskDetailsList.length,
            itemBuilder: (BuildContext context, int index) {
              TaskBeanDetails item = taskDetailsList[index];
              int itemId = int.parse(item.itemId);
              bool isShowTitle = true;
              bool isShowBottomTitle = true;
              int type = item.type;
              Color textColor = Colors.grey;
              String preText = "";
              if (type == 0) {
                textColor = Colors.red;
                preText = "阅读";
              } else if (type == 2) {
                textColor = Colors.blue;
                preText = "视频";
              } else if (type == 1) {
                textColor = Colors.deepOrange;
                preText = "练习";
              }

              if (index > 0) {
                TaskBeanDetails preItem = taskDetailsList[index - 1];
                if (item.createTimeStr == preItem.createTimeStr) {
                  isShowTitle = false;
                }
              }
              if (index < taskDetailsList.length - 1) {
                TaskBeanDetails netxItem = taskDetailsList[index + 1];
                if (item.createTimeStr == netxItem.createTimeStr) {
                  isShowBottomTitle = false;
                }
              }
              return Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    isShowTitle
                        ? Padding(
                            padding: EdgeInsets.only(bottom: 12, top: 12),
                            child: Row(
                              children: [
                                SizedBox(width: 8),
                                Container(
                                  child: Text(
                                    item.createTimeStr,
                                    style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        color: Colors.black),
                                  ),
                                ),
                              ],
                            ),
                          )
                        : SizedBox(),
                    Container(
                        color: Colors.white,
                        padding: EdgeInsets.only(left: 12, top: 12, right: 12),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Text(
                                        item.remark,
                                        style: TextStyle(
                                            fontSize: 14, color: Colors.black),
                                      ),
                                      SizedBox(
                                        height: 8,
                                      ),
                                      Text(
                                        item.itemName,
                                        style: TextStyle(
                                            fontSize: 12,
                                            color: Color(0xff666666)),
                                      ),
                                      SizedBox(
                                        height: 8,
                                      ),
                                    ],
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    if (type == 1) {
                                      NavigatorUtils.pushPage(
                                        context,
                                        MineMyScoreHisRecoderPage(
                                          extractingId: itemId,
                                        ),
                                      );
                                    }
                                  },
                                  child: Text(
                                    "$preText ",
                                    style: TextStyle(
                                        color: textColor,
                                        fontSize: 14,
                                        fontWeight: FontWeight.normal),
                                  ),
                                )
                              ],
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Text(
                                  item.createTime,
                                  style: TextStyle(
                                      fontSize: 12, color: Color(0xff666666)),
                                ),
                              ],
                            ),
                            Container(
                              width: double.infinity,
                              height: 1,
                              color: Color(0xffeeeeee),
                              margin: EdgeInsets.only(top: 10),
                            )
                          ],
                        )),
                  ],
                ),
              );
            },
          ),
        );
      },
    );
  }

  ///积分收支明细
  buildAccountWaterWidget() {
    return GetBuilder(
      id: "accountWater",
      tag: _tag,
      builder: (AccountCenterController controller) {
        List<IntegralStatBean> waterList = controller.waterList;

        bool waterListLoading = controller.waterListLoading;
        if (waterListLoading) {
          return LoadingWidget();
        }
        if (waterList.isEmpty) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  controller.requestWaterList(click: true);
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      "assets/images/2.0x/home_study.png",
                      width: 33,
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(
                      "暂无数据",
                      style: TextStyle(color: Colors.grey),
                    )
                  ],
                ),
              )
            ],
          );
        }

        return Container(
          margin: EdgeInsets.only(bottom: 8, left: 12, right: 12),
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0xFFE3F2FD), Color(0xFFBBDEFB)]),
              borderRadius: BorderRadius.all(Radius.circular(12)),
              border: Border.all(
                color: Colors.white,
              )),
          child: ListView.builder(
            itemCount: waterList.length,
            itemBuilder: (BuildContext context, int index) {
              IntegralStatBean item = waterList[index];
              bool isShowTitle = true;
              bool isShowBottomTitle = true;
              Color textColor = Colors.grey;
              String preText = "";
              if (index > 0) {
                IntegralStatBean preItem = waterList[index - 1];
                if (item.createTimeStr == preItem.createTimeStr) {
                  isShowTitle = false;
                }
              }
              if (index < waterList.length - 1) {
                IntegralStatBean netxItem = waterList[index + 1];
                if (item.createTimeStr == netxItem.createTimeStr) {
                  isShowBottomTitle = false;
                }
              }
              return Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    isShowTitle
                        ? Padding(
                            padding: EdgeInsets.only(bottom: 12, top: 12),
                            child: Row(
                              children: [
                                SizedBox(width: 8),
                                Container(
                                  child: Text(
                                    item.createTimeStr,
                                    style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        color: Colors.black),
                                  ),
                                ),
                              ],
                            ),
                          )
                        : SizedBox(),
                    Container(
                        color: Colors.white,
                        padding: EdgeInsets.only(left: 12, top: 12, right: 12),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Text(
                                        buildRemark(item),
                                        style: TextStyle(
                                            fontSize: 14, color: Colors.black),
                                      ),
                                      SizedBox(
                                        height: 8,
                                      ),
                                      Text(
                                        item.createTime,
                                        style: TextStyle(
                                            fontSize: 12,
                                            color: Color(0xff666666)),
                                      )
                                    ],
                                  ),
                                ),
                                Text(
                                  "$preText ${item.videoIntegral}分",
                                  style: TextStyle(
                                      color: textColor,
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600),
                                )
                              ],
                            ),
                            Container(
                              width: double.infinity,
                              height: 1,
                              color: Color(0xffeeeeee),
                              margin: EdgeInsets.only(top: 10),
                            )
                          ],
                        ))
                  ],
                ),
              );
            },
          ),
        );
      },
    );
  }

  String buildRemark(IntegralStatBean item) {
    if (item.remark.isNotEmpty) {
      return item.remark;
    }
    return item.systemRemark;
  }

  buildItemClass(String title, String iconData, Widget page) {
    return Expanded(
      child: GestureDetector(
        onTap: () {
          NavigatorUtils.pushPage(context, page);
        },
        child: Container(
          margin: EdgeInsets.only(top: 10, bottom: 10),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                "$iconData.png",
                width: 22,
              ),
              SizedBox(
                height: 4,
              ),
              Text(
                title,
                style: TextStyle(fontSize: 12),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
